/**
 * IndexedDB 数据库服务类
 * 用于管理SQL生成历史记录
 */
class DBService {
    constructor() {
        this.dbName = 'SQLGeneratorDB';
        this.version = 1;
        this.db = null;
        this.ready = this.initDB();
    }

    /**
     * 初始化数据库
     * @returns {Promise} 数据库初始化完成的Promise
     */
    async initDB() {
        return new Promise((resolve, reject) => {
            const request = indexedDB.open(this.dbName, this.version);

            request.onerror = (event) => {
                console.error('数据库打开失败:', event.target.error);
                reject(event.target.error);
            };

            request.onsuccess = (event) => {
                this.db = event.target.result;
                console.log('数据库连接成功');
                resolve();
            };

            request.onupgradeneeded = (event) => {
                const db = event.target.result;
                
                // 创建历史记录表
                if (!db.objectStoreNames.contains('history')) {
                    const store = db.createObjectStore('history', {
                        keyPath: 'id',
                        autoIncrement: true
                    });
                    
                    // 创建索引
                    store.createIndex('timestamp', 'timestamp', { unique: false });
                    store.createIndex('tableName', 'tableName', { unique: false });
                }
            };
        });
    }

    /**
     * 保存历史记录
     * @param {Object} record 历史记录对象
     * @returns {Promise} 保存完成的Promise
     */
    async saveHistory(record) {
        await this.ready;
        return new Promise((resolve, reject) => {
            const transaction = this.db.transaction(['history'], 'readwrite');
            const store = transaction.objectStore('history');

            // 添加时间戳
            record.timestamp = new Date().getTime();

            const request = store.add(record);

            request.onsuccess = () => resolve(request.result);
            request.onerror = () => reject(request.error);
        });
    }

    /**
     * 获取所有历史记录
     * @returns {Promise<Array>} 历史记录数组
     */
    async getAllHistory() {
        await this.ready;
        return new Promise((resolve, reject) => {
            const transaction = this.db.transaction(['history'], 'readonly');
            const store = transaction.objectStore('history');
            const request = store.index('timestamp').getAll();

            request.onsuccess = () => resolve(request.result.reverse()); // 按时间倒序
            request.onerror = () => reject(request.error);
        });
    }

    /**
     * 删除历史记录
     * @param {number} id 记录ID
     * @returns {Promise} 删除完成的Promise
     */
    async deleteHistory(id) {
        await this.ready;
        return new Promise((resolve, reject) => {
            const transaction = this.db.transaction(['history'], 'readwrite');
            const store = transaction.objectStore('history');
            const request = store.delete(id);

            request.onsuccess = () => resolve();
            request.onerror = () => reject(request.error);
        });
    }

    /**
     * 清空所有历史记录
     * @returns {Promise} 清空完成的Promise
     */
    async clearHistory() {
        await this.ready;
        return new Promise((resolve, reject) => {
            const transaction = this.db.transaction(['history'], 'readwrite');
            const store = transaction.objectStore('history');
            const request = store.clear();

            request.onsuccess = () => resolve();
            request.onerror = () => reject(request.error);
        });
    }

    /**
     * 根据表名搜索历史记录
     * @param {string} tableName 表名
     * @returns {Promise<Array>} 匹配的历史记录数组
     */
    async searchHistory(tableName) {
        await this.ready;
        return new Promise((resolve, reject) => {
            const transaction = this.db.transaction(['history'], 'readonly');
            const store = transaction.objectStore('history');
            const index = store.index('tableName');
            const request = index.getAll(tableName);

            request.onsuccess = () => resolve(request.result.reverse());
            request.onerror = () => reject(request.error);
        });
    }
} 